<template>
  <div class="home-container">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <h1>xxxxxxxxxxxxxxxxxxx</h1>
        <p>分享你的想法，发现精彩内容</p>
        <div class="banner-actions">
          <a-button 
            v-if="!userStore.isLoggedIn" 
            type="primary" 
            size="large"
            @click="$router.push('/register')"
          >
            立即注册
          </a-button>
          <a-button 
            v-if="userStore.isLoggedIn" 
            type="primary" 
            size="large"
            @click="$router.push('/write')"
          >
            开始创作
          </a-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <a-row :gutter="24">
        <!-- 左侧边栏 -->
        <a-col :xs="24" :lg="6">
          <div class="sidebar left-sidebar sticky-sidebar">
            <!-- 博客分类 -->
            <a-card title="博客分类" class="categories-card">
              <div class="categories-list">
                <a-empty v-if="categories.length === 0" description="暂无分类" />
                <a-menu v-else mode="inline">
                  <a-menu-item 
                    v-for="category in categories" 
                    :key="category.id"
                    @click="viewCategory(category.id)"
                  >
                    <span class="category-item">
                      {{ category.name }}
                      <span class="category-count">({{ category.postCount || 0 }})</span>
                    </span>
                  </a-menu-item>
                </a-menu>
              </div>
            </a-card>

            <!-- 标签云 -->
            <a-card title="标签云" class="tags-card">
              <div class="tags-list">
                <a-empty v-if="tags.length === 0" description="暂无标签" />
                <a-tag 
                  v-for="tag in tags" 
                  :key="tag.id"
                  :color="tag.color || 'blue'"
                  class="tag-item"
                  @click="viewTag(tag.id)"
                >
                  {{ tag.name }}
                </a-tag>
              </div>
            </a-card>

            <!-- 相关文章推荐 -->
            <a-card title="相关推荐" class="related-posts-card">
              <div class="related-posts-list">
                <a-empty v-if="relatedPosts.length === 0" description="暂无推荐" />
                <div 
                  v-else
                  v-for="post in relatedPosts" 
                  :key="post.id"
                  class="related-post-item"
                  @click="viewPost(post.id)"
                >
                  <h4 class="related-post-title">{{ post.title }}</h4>
                  <div class="related-post-meta">
                    <span class="post-views">
                      <EyeOutlined />
                      {{ post.viewCount || 0 }}
                    </span>
                  </div>
                </div>
              </div>
            </a-card>
          </div>
        </a-col>

        <!-- 中间内容 -->
        <a-col :xs="24" :lg="12">
          <div class="content-section">
            <div class="content-header">
              <h2>最新文章</h2>
              <!-- 搜索栏 -->
              <div class="search-bar">
                <a-input-search
                  v-model:value="searchKeyword"
                  placeholder="搜索文章..."
                  enter-button="搜索"
                  size="large"
                  @search="handleSearch"
                />
              </div>
            </div>
            
            <a-spin :spinning="loading">
              <div v-if="posts.length === 0 && !loading" class="empty-state">
                <a-empty description="暂无文章" />
              </div>
              <div v-else class="posts-list">
                <div 
                  v-for="post in posts" 
                  :key="post.id"
                  class="post-item"
                  @click="viewPost(post.id)"
                >
                  <div class="post-content">
                    <h3 class="post-title">{{ post.title }}</h3>
                    <p class="post-excerpt">{{ post.excerpt }}</p>
                    <div class="post-meta">
                      <span class="post-date">
                        <CalendarOutlined />
                        {{ formatDate(post.createdAt) }}
                      </span>
                      <span class="post-views">
                        <EyeOutlined />
                        {{ post.viewCount || 0 }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </a-spin>
          </div>
        </a-col>

        <!-- 右侧边栏 -->
        <a-col :xs="24" :lg="6">
          <div class="sidebar right-sidebar sticky-sidebar">
            <!-- 用户信息卡片 -->
            <a-card v-if="userStore.isLoggedIn" title="个人信息" class="user-card">
              <div class="user-info">
                <a-avatar 
                  :src="userStore.userInfo?.avatar" 
                  :size="64"
                  class="user-avatar"
                >
                  {{ userStore.userInfo?.nickname?.charAt(0) || 'U' }}
                </a-avatar>
                <div class="user-details">
                  <h4>{{ userStore.userInfo?.nickname }}</h4>
                  <p>{{ userStore.userInfo?.email }}</p>
                  <a-button 
                    type="link" 
                    size="small"
                    @click="$router.push('/profile')"
                  >
                    查看个人中心
                  </a-button>
                </div>
              </div>
            </a-card>

            <!-- 近期评论 -->
            <a-card title="近期评论" class="recent-comments-card">
              <div class="recent-comments-list">
                <a-empty v-if="recentComments.length === 0" description="暂无评论" />
                <div 
                  v-else
                  v-for="comment in recentComments" 
                  :key="comment.id"
                  class="comment-item"
                >
                  <div class="comment-author">
                    <a-avatar :size="24" :src="comment.author?.avatar">
                      {{ comment.author?.nickname?.charAt(0) || 'U' }}
                    </a-avatar>
                    <span class="comment-author-name">{{ comment.author?.nickname || '匿名用户' }}</span>
                  </div>
                  <div class="comment-content">{{ comment.content }}</div>
                  <div class="comment-meta">
                    <span class="comment-date">{{ formatDate(comment.createdAt) }}</span>
                  </div>
                </div>
              </div>
            </a-card>

            <!-- 热门标签 -->
            <a-card title="热门标签" class="tags-card">
              <div class="tags-list">
                <a-tag 
                  v-for="tag in tags" 
                  :key="tag.id"
                  :color="tag.color || 'blue'"
                  class="tag-item"
                  @click="viewTag(tag.id)"
                >
                  {{ tag.name }}
                </a-tag>
              </div>
            </a-card>

            <!-- 统计信息 -->
            <a-card title="网站统计" class="stats-card">
              <div class="stats-list">
                <div class="stat-item">
                  <span class="stat-label">总文章数</span>
                  <span class="stat-value">{{ totalPosts }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">总用户数</span>
                  <span class="stat-value">{{ totalUsers }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">今日访问</span>
                  <span class="stat-value">{{ todayViews }}</span>
                </div>
              </div>
            </a-card>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { 
  UserOutlined, 
  CalendarOutlined, 
  EyeOutlined 
} from '@ant-design/icons-vue'
import { useUserStore } from '@/stores'
import { postApi, categoryApi, tagApi, statisticsApi, commentApi } from '@/api'
import type { Post, Category, Tag, Comment } from '@/types'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const posts = ref<Post[]>([])
const categories = ref<Category[]>([])
const tags = ref<Tag[]>([])
const relatedPosts = ref<Post[]>([])
const recentComments = ref<Comment[]>([])
const totalPosts = ref(0)
const totalUsers = ref(0)
const todayViews = ref(0)
const searchKeyword = ref('') // 添加搜索关键词

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 查看文章详情
const viewPost = (postId: number) => {
  router.push(`/post/${postId}`)
}

// 查看分类
const viewCategory = (categoryId: number) => {
  router.push(`/category/${categoryId}`)
}

// 查看标签
const viewTag = (tagId: number) => {
  router.push(`/tag/${tagId}`)
}

// 处理搜索
const handleSearch = () => {
  loadData()
}

// 解析统计数据
const parseStatisticsData = (data: any) => {
  // 如果数据是一个对象，尝试从中提取用户数和访问量
  if (data && typeof data === 'object') {
    // 递归搜索对象中的数字值
    const findNumericValue = (obj: any, keywords: string[]): number => {
      if (typeof obj === 'number') {
        return obj;
      }
      
      if (obj && typeof obj === 'object') {
        // 直接检查对象的属性
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            const lowerKey = key.toLowerCase();
            if (keywords.some(keyword => lowerKey.includes(keyword))) {
              if (typeof obj[key] === 'number') {
                return obj[key];
              }
            }
          }
        }
        
        // 递归检查嵌套对象
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            const result = findNumericValue(obj[key], keywords);
            if (result !== 0) {
              return result;
            }
          }
        }
      }
      
      return 0;
    };
    
    // 尝试查找用户总数
    totalUsers.value = findNumericValue(data, ['user', 'member', '注册']);
    
    // 尝试查找今日访问量
    todayViews.value = findNumericValue(data, ['visit', 'view', '访问', '浏览']);
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  
  try {
    // 并行加载文章列表、分类列表和标签列表
    const [postsResponse, categoriesResponse, tagsResponse, statsResponse, commentsResponse] = await Promise.allSettled([
      postApi.getPostList({
        pageNo: '1',
        pageSize: '10',
        keyword: searchKeyword.value, // 使用搜索关键词
        status: 'PUBLISHED',
        categoryId: '',
        tagId: '',
        orderBy: 'createdAt',
        asc: 'false'
      }),
      categoryApi.getCategoryList({ page: '1', size: '10' }),
      tagApi.getTagList({ pageNo: '1', pageSize: '10' }),
      statisticsApi.getOverview(),
      commentApi.getCommentTree(0) // 获取所有评论，postId=0表示获取所有评论
    ])
    
    // 处理文章数据
    if (postsResponse.status === 'fulfilled') {
      posts.value = postsResponse.value.data.result || []
      totalPosts.value = postsResponse.value.data.total || 0
      
      // 模拟相关文章推荐（取前3篇）
      relatedPosts.value = [...posts.value].slice(0, 3)
    }
    
    // 处理分类数据
    if (categoriesResponse.status === 'fulfilled') {
      categories.value = categoriesResponse.value.data.result || []
    }
    
    // 处理标签数据
    if (tagsResponse.status === 'fulfilled') {
      tags.value = tagsResponse.value.data.result || []
    }
    
    // 处理统计数据
    if (statsResponse.status === 'fulfilled') {
      const stats = statsResponse.value.data
      console.log('完整统计数据:', JSON.stringify(stats, null, 2)) // 输出完整数据结构
      
      // 尝试解析统计数据
      parseStatisticsData(stats)
    } else {
      console.error('统计数据加载失败')
    }
    
    // 处理评论数据
    if (commentsResponse.status === 'fulfilled') {
      // 取最新的3条评论
      recentComments.value = [...commentsResponse.value.data].slice(0, 3)
    }
    
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.home-container {
  min-height: 100vh;
}

.welcome-banner {
  background: linear-gradient(135deg, #008080, #00cccc, #00b8b8);
  color: white;
  padding: 80px 0;
  text-align: center;
  margin-bottom: 40px;
}

.banner-content h1 {
  font-size: 48px;
  font-weight: 700;
  margin: 0 0 16px 0;
}

.banner-content p {
  font-size: 20px;
  margin: 0 0 32px 0;
  opacity: 0.9;
}

.banner-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.content-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

.search-bar {
  flex: 1;
  max-width: 300px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-item {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.post-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.post-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 12px 0;
  color: #262626;
}

.post-excerpt {
  color: #8c8c8c;
  line-height: 1.6;
  margin: 0 0 16px 0;
}

.post-meta {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #8c8c8c;
}

.post-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 添加sticky定位实现悬浮吸顶效果 */
.sticky-sidebar {
  position: sticky;
  top: 80px;
  align-self: flex-start;
}

.left-sidebar .categories-card,
.left-sidebar .tags-card,
.left-sidebar .related-posts-card,
.right-sidebar .recent-comments-card,
.right-sidebar .user-card,
.right-sidebar .tags-card,
.right-sidebar .stats-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
}

.categories-list {
  max-height: 300px;
  overflow-y: auto;
}

.category-item {
  display: flex;
  justify-content: space-between;
}

.category-count {
  color: #8c8c8c;
  font-size: 12px;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s;
}

.tag-item:hover {
  transform: scale(1.05);
}

.related-posts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.related-post-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.related-post-item:last-child {
  border-bottom: none;
}

.related-post-title {
  font-size: 14px;
  font-weight: 500;
  margin: 0 0 4px 0;
  color: #262626;
  line-height: 1.4;
}

.related-post-meta {
  font-size: 12px;
  color: #8c8c8c;
  display: flex;
  align-items: center;
  gap: 4px;
}

.recent-comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.comment-author-name {
  font-size: 13px;
  font-weight: 500;
  color: #595959;
}

.comment-content {
  font-size: 13px;
  color: #262626;
  line-height: 1.4;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.comment-meta {
  font-size: 12px;
  color: #8c8c8c;
}

.user-card .user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-details h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
}

.user-details p {
  margin: 0 0 8px 0;
  color: #8c8c8c;
  font-size: 14px;
}

.stats-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  color: #8c8c8c;
  font-size: 14px;
}

.stat-value {
  font-weight: 600;
  color: #262626;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .banner-content h1 {
    font-size: 32px;
  }
  
  .banner-content p {
    font-size: 16px;
  }
  
  .main-content {
    padding: 0 16px;
  }
  
  .content-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar {
    max-width: none;
  }
  
  .post-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  /* 在小屏幕上禁用sticky效果 */
  .sticky-sidebar {
    position: static;
  }
}
</style>